package com.harvey.study.data.structure.datastructure.queue;

import com.harvey.study.data.structure.datastructure.linkedlist.Node;

/**
 * 
 * date: 2021-04-28
 * desc: 通过单项链表的方式实现队列
 */
public class LinkedQueue<T> {
    private int length;
    private Node<T> rear;
    private Node<T> front;


    public void enQueue(T data){
        if(isEmpty()){
            this.front = new Node<T>(data,null);
            this.rear = this.front;
            length++;
            return;
        }
        Node<T> p = new Node<T>(data,null);
        //这块有个注意的地方，一旦rail设置了next属性，
        //因为front节点与rail节点指向了同一个node节点，
        //持有同一个结点的一个引用，因此front节点next属性也被填充
        this.rear.next = p;
        this.rear = p;
        length++;
    }

    public T deQueue(){
        if(isEmpty()){
            return null;
        }
        T data = this.front.data;
        this.front = this.front.next;
        this.length --;
        return data;
    }

    public T getHead(){
        if(isEmpty()){
            return null;
        }
        return this.front.data;
    }

    public boolean isEmpty(){
        return this.length == 0;
    }

    public int size(){
        return this.length;
    }

    public void clear(){
        this.rear = this.front = null;
        this.length = 0;
    }



    public static void main(String[] args) {
        LinkedQueue<String> linkedlist = new LinkedQueue<String>();
        linkedlist.enQueue("a");
        linkedlist.enQueue("b");
        linkedlist.enQueue("c");
        linkedlist.enQueue("d");
        linkedlist.enQueue("e");
        linkedlist.enQueue("f");
        linkedlist.enQueue("g");
        linkedlist.enQueue("h");

        System.out.println(linkedlist.getHead());

        linkedlist.clear();


        linkedlist.enQueue("d");
        linkedlist.enQueue("e");
        linkedlist.enQueue("f");
        linkedlist.enQueue("g");
        linkedlist.enQueue("h");
        
        int size = linkedlist.size();
        for(int i=0;i<size;i++){
            System.out.println(linkedlist.deQueue());
        }




        System.out.println(linkedlist.size());


    }
    

}
